<?php
header("Content-Type: application/json");

// 数据库配置
$host = 'localhost';
$dbname = 'test';
$user = 'root';
$password = 'root';

try {
    // 连接数据库
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 解析请求方法
    $method = $_SERVER['REQUEST_METHOD'];
    $input = json_decode(file_get_contents("php://input"), true);

    // 路径解析，提取用户 ID（如果存在）
    $path = explode('/', trim($_SERVER['PATH_INFO'], '/'));
    $resource = $path[0];
    $id = isset($path[1]) ? intval($path[1]) : null;

    if ($resource !== 'users') {
        http_response_code(404);
        echo json_encode(["error" => "Resource not found"]);
        exit;
    }

    switch ($method) {
        case 'GET':
            if ($id) {
                // 获取单个用户
                $stmt = $pdo->prepare("SELECT * FROM user WHERE id = :id");
                $stmt->execute(['id' => $id]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                if ($user) {
                    echo json_encode($user);
                } else {
                    http_response_code(404);
                    echo json_encode(["error" => "User not found"]);
                }
            } else {
                // 获取所有用户
                $stmt = $pdo->query("SELECT * FROM user");
                $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
                echo json_encode($users);
            }
            break;

        case 'POST':
            // 创建新用户
            if (isset($input['name'], $input['password'], $input['age'])) {
                $stmt = $pdo->prepare("INSERT INTO user (name, password, age) VALUES (:name, :password, :age)");
                $stmt->execute([
                    'name' => $input['name'],
                    'password' => $input['password'],
                    'age' => $input['age']
                ]);
                http_response_code(201);
                echo json_encode(["id" => $pdo->lastInsertId()]);
            } else {
                http_response_code(400);
                echo json_encode(["error" => "Invalid input"]);
            }
            break;

        case 'PUT':
            // 更新用户信息
            if ($id && isset($input['name'], $input['password'], $input['age'])) {
                $stmt = $pdo->prepare("UPDATE user SET name = :name, password = :password, age = :age WHERE id = :id");
                $stmt->execute([
                    'name' => $input['name'],
                    'password' => $input['password'],
                    'age' => $input['age'],
                    'id' => $id
                ]);
                if ($stmt->rowCount()) {
                    echo json_encode(["message" => "User updated successfully"]);
                } else {
                    http_response_code(404);
                    echo json_encode(["error" => "User not found"]);
                }
            } else {
                http_response_code(400);
                echo json_encode(["error" => "Invalid input or missing ID"]);
            }
            break;

        case 'DELETE':
            // 删除用户
            if ($id) {
                $stmt = $pdo->prepare("DELETE FROM user WHERE id = :id");
                $stmt->execute(['id' => $id]);
                if ($stmt->rowCount()) {
                    echo json_encode(["message" => "User deleted successfully"]);
                } else {
                    http_response_code(404);
                    echo json_encode(["error" => "User not found"]);
                }
            } else {
                http_response_code(400);
                echo json_encode(["error" => "Missing ID"]);
            }
            break;

        default:
            http_response_code(405);
            echo json_encode(["error" => "Method not allowed"]);
            break;
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(["error" => "Database error: " . $e->getMessage()]);
}
?>
